<?php
/**
 *  Create On 2014-11-11
 *  Author Yiwei
 *  QQ:1006629314
 **/
class DB{
	protected $_dbConf = null;
	protected $_conn = null;
	
	protected $_qtable = null;
	protected $_qindex = null;
	
	public function __construct($dbArr){
		$this->_dbConf["_host"]	=	$dbArr['host'];
		$this->_dbConf["_database"]	=	$dbArr['database'];
		$this->_dbConf["_user"]	=	$dbArr['user'];
		$this->_dbConf["_pw"]	=	$dbArr['pw'];
		$this->_dbConf["_charset"]	=	$dbArr['charset'];
	}

	function open(){
		$conn = mysql_pconnect($this->_dbConf["_host"], $this->_dbConf["_user"], $this->_dbConf["_pw"]) or die("connect error!");
		mysql_select_db($this->_dbConf["_database"], $conn)or die('error '.$this->_dbConf["_database"].mysql_error());
		mysql_query("set names " . $this->_dbConf["_charset"]);
		$this->_conn = $conn;
	}
	
	public function insert($sql){
		$result = mysql_query($sql,$this->_conn );
		if(!$result)	return false;
		$lastId = mysql_insert_id();
		return $lastId;
	}
	
	public function fetchRow($sql){
		$result = mysql_query($sql,$this->_conn );
		if($result){
			$row = mysql_fetch_assoc($result);
			return $row;
		}
		return false;
	}
	
	public function setIndex($index,$table,$filter=null){
		$this->_qindex = $index;
		$this->_qtable = $table;
		$sql = 'SELECT '.$index.' FROM '.$table;
		if($filter){
			$sql.=" WHERE ".$filter." ";
		}
		return mysql_query($sql,$this->_conn);
	}
	
	public function getRow($result,$row){
		mysql_data_seek($result, $row);
		$index = mysql_fetch_row($result);
		$sql = 'SELECT * FROM '.$this->_qtable.' WHERE '.$this->_qindex.'='.$index['0'];
		return $this->fetchRow($sql);
	}
	
	public function getTotal($table,$filter=null){
	
		$return = 0;
		$sql="select count(*) as num from `".$table."` ";
		if($filter){
			$sql.="WHERE ".$filter." ";
		}
		$row = $this->fetchRow($sql);
		if( $row ){
			$return = $row["num"];
		}
		return $return;
	}
	
	
	public function close(){
		if($this->_conn)	mysql_close($this->_conn);
	}
	
}